package com.lifeservice.wxapi;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lifeservice.common.config.LifeServiceConfig;
import com.lifeservice.common.core.domain.AjaxResult;
import com.lifeservice.common.core.redis.RedisCache;
import com.lifeservice.common.utils.DateUtils;
import com.lifeservice.common.utils.HmacSHA256Util;
import com.lifeservice.common.utils.SnowFlakeUtil;
import com.lifeservice.common.utils.StringUtils;
import com.lifeservice.common.utils.http.HttpUtils;
import com.lifeservice.console.domain.LifeWxappConfig;
import com.lifeservice.console.domain.LifeWxuser;
import com.lifeservice.console.service.ILifeWxappConfigService;
import com.lifeservice.console.service.ILifeWxuserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx")
@Slf4j
public class WxLoginController {
    @Autowired
    private ILifeWxuserService wxuserService;

    @Autowired
    private ILifeWxappConfigService wxappConfigService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private LifeServiceConfig lifeServiceConfig;

    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     *
     * @param object
     * @return
     */
    @PostMapping("/wxlogin")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult wxLogin(@RequestBody JSONObject object) {
        // 微信官方提供的微信小程序登录授权时使用的URL地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        /**
         * 拼接需要的参数
         * appid = AppID 你自己的微信小程序APPID
         * js_code = AppSecret 你自己的微信APP密钥
         * grant_type=authorization_code = code 微信官方提供的临时凭证
         */
        LifeWxappConfig wxconfig = wxappConfigService.selectWxappConfig();
        String params = StringUtils.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", wxconfig.getAppid(), wxconfig.getAppSecret(), object.get("code"));
        //开始发起网络请求,生活服务管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url, params);
        log.info("wx接口调用情况：" + res);
        JSONObject jsonObject = JSON.parseObject(res);
        String session_key = (String) jsonObject.get("session_key");
        String openid = (String) jsonObject.get("openid");
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.error("未获取到openid");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("token", openid);
        data.put("session_key", session_key);
        data.put("openid", openid);
        data.put("state", true);
        data.put("nickName", object.get("nickName"));
        data.put("avatarUrl", object.get("avatarUrl"));
        data.put("phoneno", object.get("phoneno"));
        data.put("gender", object.get("gender"));
        /**先通过openid来查询是否存在*/
        LifeWxuser wxuserInDb = wxuserService.selectWxuserOpenID(openid);
        if (wxuserInDb == null) {
            /**如果不存在就插入到我们的数据库里*/
            LifeWxuser wxuser = new LifeWxuser();
            wxuser.setId(SnowFlakeUtil.getInstance().nextId());
            wxuser.setNickname(String.valueOf(object.get("nickName")));
            wxuser.setGender((Integer) object.get("gender"));
            wxuser.setAvatar(String.valueOf(object.get("avatarUrl")));
            wxuser.setOpenid(openid);
            wxuser.setPhoneno(null == object.get("phoneno") ? null : String.valueOf(object.get("phoneno")));
            wxuser.setCreateTime(DateUtils.getNowDate());
            wxuser.setCreateBy("wx");
            // 用户注册时，带上tag
            List<String> tagList = (ArrayList) object.get("tags");
            if (StringUtils.isNotEmpty(tagList)) {
                data.put("tags", tagList);
                wxuser.setTag(JSON.toJSONString(tagList));
            }
            data.put("userId", wxuser.getId());
            wxuserService.insertLifeWxuser(wxuser);
            String hmacToken = HmacSHA256Util.hmacSHA256(lifeServiceConfig.getHmacKey(), openid);
            redisCache.setCacheObject(hmacToken, wxuser);
        } else {
            data.put("nickName", wxuserInDb.getNickname());
            data.put("avatarUrl", wxuserInDb.getAvatar());
            data.put("phoneno", wxuserInDb.getPhoneno());
            data.put("gender", wxuserInDb.getGender());
            /**如果存在就更新数据库里原有的数据*/
            wxuserInDb.setNickname(wxuserInDb.getNickname());
            wxuserInDb.setGender(wxuserInDb.getGender());
            wxuserInDb.setAvatar(wxuserInDb.getAvatar());
            wxuserInDb.setPhoneno(wxuserInDb.getPhoneno());
            wxuserInDb.setUpdateTime(DateUtils.getNowDate());
            wxuserInDb.setUpdateBy("wx");
            List<String> tagInsertList = new ArrayList<>();
            if (StringUtils.isNotEmpty(wxuserInDb.getTag())) {
                List<String> oldTagList = JSON.parseArray(wxuserInDb.getTag(), String.class);
                List<String> tagList = (ArrayList) object.get("tags");
                if (StringUtils.isNotEmpty(tagList)) {
                    tagList.removeAll(oldTagList);
                    oldTagList.addAll(tagList);
                }
                tagInsertList = oldTagList;
            } else {
                tagInsertList = (ArrayList) object.get("tags");
            }
            data.put("tags", tagInsertList);
            wxuserInDb.setTag(JSON.toJSONString(tagInsertList));
            wxuserService.updateLifeWxuser(wxuserInDb);
            data.put("userId", wxuserInDb.getId());
            String hmacToken = HmacSHA256Util.hmacSHA256(lifeServiceConfig.getHmacKey(), openid);
            redisCache.setCacheObject(hmacToken, wxuserInDb);
        }
        if (null != data.get("phoneno") && "null".equals(data.get("phoneno"))) {
            data.put("phoneno", null);
        }
        return AjaxResult.success(data);
    }

    @PostMapping("/wxUpdateUser")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult wxUpdateUser(HttpServletRequest request, @RequestBody JSONObject object) {
        String token = request.getHeader("token");
        LifeWxuser wxuserInDb = wxuserService.selectWxuserOpenID(token);

        if (wxuserInDb == null) {
            return AjaxResult.error("用户不存在");
        }

        // 以下信息更新
        wxuserInDb.setNickname(String.valueOf(object.get("nickName")));
        wxuserInDb.setGender(Integer.valueOf(String.valueOf(object.get("gender"))));
        wxuserInDb.setAvatar(String.valueOf(object.get("avatarUrl")));
        wxuserInDb.setPhoneno(null == object.get("phoneno") ? null : String.valueOf(object.get("phoneno")));
        // 下面信息保留不变
        wxuserInDb.setUpdateTime(DateUtils.getNowDate());
        wxuserInDb.setUpdateBy(String.valueOf(object.get("nickName")));
        wxuserInDb.setTag(wxuserInDb.getTag());

        wxuserService.updateLifeWxuser(wxuserInDb);

        return AjaxResult.success("更新成功");
    }
}
